(async ()=>{
    let key = ''//搜索关键字
    let sort = 0 //排序方式
    let brandIds = ''//品牌列表
    let pageNum = 1 //当前页
    let productsDom = document.querySelector('#products')
    let total = 0,rows = []

    //focus 获取焦点 blur失去焦点
    const searchIcon = document.querySelector('.ss');  
    const placeholderText = '搜索关键字';  
  
        keyInput.addEventListener('focus', function() {  
            // 当输入框获得焦点时（即被点击时）  
            if (this.value === placeholderText) {  
                // 如果输入框的值是默认的占位符文本，则清空它  
                this.value = '';  
            }  
            // 隐藏搜索图标（如果需要）  
            searchIcon.style.display = 'none';  
        });  
  
        keyInput.addEventListener('blur', function() {  
            // 当输入框失去焦点时  
            if (this.value === '') {  
                // 如果输入框是空的，则恢复默认的占位符文本和搜索图标  
                this.value = placeholderText;  
                searchIcon.style.display = 'block';  
            }  
        });  

    //切换排序
    let sorts = document.querySelectorAll('.sort')
    let sortActive = sorts[0]
    for(let i = 0; i < sorts.length; i++){
        sorts[i].addEventListener('click',(event) => {
            sort = event.target.dataset.sorted
            productsDom.innerHTML = ''
            pageNum = 1
            getList()
            sortActive.className = 'sort'
            sortActive = event.target
            sortActive.className = 'sort active'
        })
    }

    //品牌
    let dialogContent = document.querySelector('#dialogContent')
    let brands = await (await fetch(`http://localhost:3001/brands`)).json()
    let brandActive = null
    for(let i = 0; i < brands.length; i ++){
        let brand = document.createElement('div')
        brand.className = 'brand'
        brand.innerHTML = `
            <img src="http://localhost:3001${brands[i].img}" />
            <div>${brands[i].name}</div>
        `
        //按品牌选择
        brand.addEventListener('click',event => {
            brandIds = brands[i]._id
            productsDom.innerHTML = ''
            pageNum = 1
            getList()
            document.querySelector('#dialog').style.display = 'none'

            //
            if(brandActive) brandActive.className = 'brand'
            brandActive = event.target
            brandActive.className = 'brand active'
        })

        dialogContent.appendChild(brand)
    }

    //打开弹框
    document.querySelector('#openDialog').addEventListener('click',event => {
        document.querySelector('#dialog').style.display = 'block'
    })
    //关闭弹框
    document.querySelector('#dialogCover').addEventListener('click',event => {
        document.querySelector('#dialog').style.display = 'none'
    })

    async function getList() {  
        try {  
            let res = await fetch(`http://localhost:3001/products?key=${key}&sorted=${sort}&brandIds=${brandIds}&pageNum=${pageNum}`);  
            if (!res.ok) {  
                throw new Error('Network response was not ok.');  
            }  
            let data = await res.json();  
      
            // 确保 data 和 data.rows 是已定义的  
            if (!data || !Array.isArray(data.rows)) {  
                throw new Error('Invalid response data format.');  
            }  
      
            // 清空之前的产品列表  
            productsDom.innerHTML = '';  
      
            // 遍历返回的产品数据  
            data.rows.forEach((product, index) => {  
                // 创建一个新的 child-box 容器  
                let childBox = document.createElement('div');  
                childBox.className = `child-box${index + 1}`; // 使用索引给每个box一个不同的类名  
      
                // 创建子元素并设置内容  
                let titleDiv = document.createElement('div');  
                titleDiv.className = 't';  
                let titleImg = document.createElement('img');  
                titleImg.src = `http://localhost:3001${product.productImgs}`; // 假设图片路径需要拼接  
                titleDiv.appendChild(titleImg);  
                childBox.appendChild(titleDiv);  
      
                let sc1 = document.createElement('div');  
                sc1.className = 'sc1';  
                sc1.textContent = product.productName; // 产品名称  
                childBox.appendChild(sc1);  
      
                let lb = document.createElement('div');  
                lb.className = 'lb';  
      
                let sc2 = document.createElement('div');  
                sc2.className = 'sc2';  
                sc2.textContent = `￥${(product.salePrice / 100).toFixed(2)}`; // 格式化后的售价  
                lb.appendChild(sc2);    

                // 创建并添加价格信息  
                let sc3 = document.createElement('div');  
                sc3.className = 'sc3';  
                sc3.innerHTML = `   
                   <img src="/2024/images/购物车juse.png"> 
                `;  
                lb.appendChild(sc3);  
      
                childBox.appendChild(lb);
              

      
                // 将 child-box 添加到 productsDom 中  
                productsDom.appendChild(childBox);  
                childBox .addEventListener('click',event =>{
                    //window.open(`./spxq.html?productId=${res.rows[i].productId}`)
                     location.href=`./shangpinxiangqing.html?productId=${product.productId}`
    //            console.log(res.rows[i].productId)
                })
            });  
        } catch (error) {  
            console.error('Error fetching and rendering products:', error);  
        }  
    }
      
    // 初始调用以渲染产品列表  
    getList()
    
})()